package com.zhenhe.core.common.log;

import java.util.Arrays;
import java.util.List;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.zhenhe.core.common.utils.StringUtils;

@Aspect
@Component
public class ServiceLog {

	private static final Logger log = LoggerFactory.getLogger("service");
	
	@Pointcut("bean(*Service)")  
    public void serviceLog() {  
    } 
	
	@SuppressWarnings("rawtypes")
	@Around("serviceLog()")
	public Object doAround(ProceedingJoinPoint pjd) throws Throwable {
		String methodName = pjd.toShortString();
		boolean containPassword = StringUtils.indexOfIgnoreCase(pjd.getSignature().getName(), "password")!= -1;
		List<Object> args = Arrays.asList(pjd.getArgs());
		long now = System.currentTimeMillis();
		Object ret = null;
		try{
			if(args.size()>0){
				ret = pjd.proceed(pjd.getArgs());
			}else{
				ret = pjd.proceed();
			}
		}catch(Throwable e){
			if(containPassword){
				args=null;
			}
			long cost = System.currentTimeMillis()-now;
			log.error("执行{}出错,参数为{},错误信息:{},耗时{}毫秒", methodName,args,e.getMessage(),cost);
			throw e;
		}
		if(containPassword){
			args=null;
		}
		long cost = System.currentTimeMillis()-now;
		if(ret!= null && ret instanceof List){
			List r = (List) ret;
			log.info("执行{}完成，入参为{},返回长度：{},执行耗时{}毫秒", methodName,args,r.size(),cost);
		}
		log.info("执行{}完成，入参为{},返回{},执行耗时{}毫秒", methodName,args,ret,cost,ret);
		return ret;
	}
}
